import java.util.LinkedList;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-05-24
 * Time: 9:14
 */

public class Solution {
    public int[][] updateMatrix(int[][] mat) {
        int row = mat.length;
        int col = mat[0].length;
        int[][] ans = new int[row][col];
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[row][col];
        // 将所有的 0 作为 源节点
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (mat[i][j] == 0){
                    queue.add(new int[]{i, j});
                    // 注意不要忘了将这几个位置设置为  true
                    visited[i][j] = true;
                }
            }
        }

        int[][] next = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        // 从 0 开始扩散
        while (!queue.isEmpty()){
            int[] temp = queue.poll();
            int x1 = temp[0];
            int y1 = temp[1];
            for (int i = 0; i < 4; i++) {
                int x = x1 + next[i][0];
                int y = y1 + next[i][1];
                if (x < 0 || x >= mat.length || y < 0 || y >= mat[0].length){
                    continue;
                }
                // 没有遍历过的再进行操作
                if (!visited[x][y]){
                    visited[x][y] = true;
                    ans[x][y] = ans[x1][y1] + 1;
                    queue.add(new int[]{x, y});
                }
            }
        }
        return ans;
    }
}
